package com.broadsoft.platform.wfengine.runtime.nodehandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broadsoft.platform.wfengine.NodeType;
import com.broadsoft.platform.wfengine.SubflowType;
import com.broadsoft.platform.wfengine.parser.ParsedWorkflowDefinition;
import com.broadsoft.platform.wfengine.runtime.WfContext;
import com.broadsoft.platform.wfengine.runtime.WfEngine;
import com.broadsoft.platform.wfengine.runtime.impl.NodeExecutionServiceImpl;

public class SubFlowNodeExecutionHandler implements INodeExecutionHandler {

    private final static Logger logger = LoggerFactory.getLogger(NodeExecutionServiceImpl.class);

    public SubFlowNodeExecutionHandler(ParsedWorkflowDefinition parsedWorkflowInfo,WfEngine wfEngine) {
        this.parsedWorkflowInfo = parsedWorkflowInfo;
        this.wfEngine=wfEngine;

    }

    @Override
    public NodeType executeNode(NodeType currentNode, WfContext flowContext)  {
        if (logger.isTraceEnabled()) {
            logger.trace("The method[executeNode] begin");
        }
        flowContext.setPreviousNode(currentNode); 
        WfContext subflowContext =new WfContext();
        subflowContext.setParentWfContext(flowContext); 
        //
        SubflowType subflowType= ((SubflowType)currentNode);
        String subflowName=subflowType.getFlow(); 
        try {
            wfEngine.start(subflowName, subflowContext);
        } catch (Exception e) { 
            e.printStackTrace();
        } 
        //
        NodeType nextNodeType=parsedWorkflowInfo.getNodeTypeByName(flowContext.getWorkflowType().getName(), currentNode.getDestNode().get(0));
        
        if (logger.isTraceEnabled()) { 
            logger.trace("The local variable[nextNodeType] is {}.",nextNodeType);
            logger.trace("The method[executeNode] end");
        }
        return nextNodeType;
    }

    private ParsedWorkflowDefinition parsedWorkflowInfo;

    public ParsedWorkflowDefinition getParsedWorkflowInfo() {
        return parsedWorkflowInfo;
    }

    public void setParsedWorkflowInfo(ParsedWorkflowDefinition parsedWorkflowInfo) {
        this.parsedWorkflowInfo = parsedWorkflowInfo;
    }
    
    private WfEngine wfEngine;

    public WfEngine getWfEngine() {
        return wfEngine;
    }

    public void setWfEngine(WfEngine wfEngine) {
        this.wfEngine = wfEngine;
    }

}
